package com.yc.project1_matrix.group;

import java.util.ArrayList;
import java.util.List;
////按cpu核数划分线程
public class ParallerGroupMultiplier {
    public static void multiply(double[][] matrix1,double[][] matrix2,double[][]result) throws InterruptedException {
        //将线程存储在集合里
        List<Thread> threads= new ArrayList<Thread>();
        //矩阵1的行列
        int rows1= matrix1.length;
        int column1=matrix1[0].length;
        //矩阵2的行列
        int rows2= matrix2.length;
        int column2=matrix2[0].length;
        //获取cpu的核数
        Runtime r=Runtime.getRuntime();//静态单例  Runtime代表当前运行的jvm环境
        int numThread =r.availableProcessors();
        System.out.println("总共有"+numThread);
        //计算每个线程要执行运算行的起始和终止
        int startIndex,endIndex,step;
        step =rows1/numThread;
        startIndex=0;
        endIndex=step;
        //循环numThreads次，每次启动一 个线程， 指定此线 程运行的范围
        for (int i=0;i<numThread;i++) {
            //启动任务
            GroupMultiplierTask gmt = new GroupMultiplierTask(result, matrix1, matrix2, startIndex, endIndex);
            Thread t = new Thread(gmt);
            t.start();
            threads.add(t);
            //计算下一个线程的范围
            startIndex =endIndex;
            //rows1=2000
            endIndex = i==numThread-2? rows1: endIndex + step;
            System.out.println("第"+i+"个线程的计算范围为："+startIndex+"-"+endIndex);
        }
        for (Thread t:threads){
            t.join();
        }
    }
}
